package com.yupi.springbootinit.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolExecutorConfig {


    /*
     int corePoolSize 核心线程数
     int maximumPoolSize 最大线程数
     long keepAliveTime 非核心线程空闲存活时间
     TimeUnit unit keepAliveTime的时间单位
     BlockingQueue<Runnable> workQueue 任务队列，被提交但尚未被执行的任务
     ThreadFactory threadFactory 表示生成线程池的线程工厂，用于设置创建的线程的名称
     RejectedExecutionHandler handler 表示当拒绝处理任务时的策略，任务队列满时，我们采取怎么样的措施，比如抛出异常。。。。
    * */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        // 创建一个线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;
            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("线程" + count);
                count++;
                return thread;
            }
        };
        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4), threadFactory);
        return threadPoolExecutor;
    }
}
